import datetime
import json
import time

from django.db import connection
from django.http import JsonResponse
from django.http.response import StreamingHttpResponse
from django.shortcuts import render

from Book.models import Book
from WebSite.BaseView import BaseView
from WebSite.commonUtil import LayuiTableData, ResponseJson


class IndexPage(BaseView):
    def get(self, request):
        return render(request, 'bookIndex.html')


class ListAllBooks(BaseView):
    def post(self, request):
        body_unicode = request.body.decode('utf-8')
        body = json.loads(body_unicode)
        page = body['page'] if 'page' in body else 1
        pageSize = body['pageSize'] if 'pageSize' in body else 10
        bookName = body['bookName'] if 'bookName' in body and body['bookName'] is not None else ''
        bookType = body['bookType'] if 'bookType' in body and body['bookType'] is not None else ''
        bookPublishDate = body['bookPublishDate'] if 'bookPublishDate' in body and body[
            'bookPublishDate'] is not None else ''
        search_sql = self.get_query_sql(bookName, bookType, bookPublishDate, page, pageSize)
        search_count_sql = self.get_query_count_sql(bookName, bookType, bookPublishDate)

        cursorCount = connection.cursor()
        cursor = connection.cursor()

        cursor.execute(search_sql)
        cursorCount.execute(search_count_sql)

        bookList = cursor.fetchall()
        totalCount = cursorCount.fetchone()
        bookArr = []
        if bookList is not None:
            for book in bookList:
                itemJson = {
                    'bookId': book[0],
                    'bookName': book[1],
                    'bookPrice': book[2],
                    'bookTypeId': book[3],
                    'bookCount': book[4],
                    'bookPublish': book[5],
                    'bookPublishDate': book[6],
                    'bookIntroduction': book[7],
                    'bookImagePath': book[8],
                    'createTime': book[9],
                    'updateTime': book[10]
                }
                bookArr.append(itemJson)
        resultData = LayuiTableData(0, "", totalCount[0], bookArr).getJsonData()
        return JsonResponse(resultData, safe=False)

    # book = Book.objects.all()
    # if barcode != '':
    #     book = book.filter(barcode__contains=barcode)
    # if bookName != '':
    #     book = book.filter(bookName__contains=bookName)
    # if publishDate != '':
    #     book = book.filter(publishDate__contains=publishDate)
    # if bookTypeObj_bookTypeId != '0':
    #     book = book.filter(bookTypeObj=bookTypeObj_bookTypeId)

    @staticmethod
    def get_query_sql(bookName, bookType, bookPublishDate, page, pageSize):
        search_sql = "select book_id,book_name,book_price,book_type_id,book_count" \
                     ",book_publish,book_publish_date,book_introduction,book_image_path" \
                     ",create_time,update_time from t_book where 1=1 "
        if len(bookName) > 0:
            search_sql = search_sql + " and book_name='" + bookName + "'"
        if len(bookType) > 0:
            search_sql = search_sql + " and book_type_id='" + bookType + "'"
        if len(bookPublishDate) > 0:
            search_sql = search_sql + " and date_format(book_publish_date,'%Y-%m-%d')='" + bookPublishDate + "'"
        search_sql = search_sql + " limit " + str((page - 1) * pageSize) + "" + str(page * pageSize)
        return search_sql

    @staticmethod
    def get_query_count_sql(bookName, bookType, bookPublishDate):
        search_sql = "select count(*) from t_book where 1=1 "
        if len(bookName) > 0:
            search_sql = search_sql + " and book_name='" + bookName + "'"
        if len(bookType) > 0:
            search_sql = search_sql + " and book_type_id='" + bookType + "'"
        if len(bookPublishDate) > 0:
            search_sql = search_sql + " and date_format(book_publish_date,'%Y-%m-%d')='" + bookPublishDate + "'"
        return search_sql


class AddBook(BaseView):
    def post(self, request):
        resultData = ResponseJson("true", "操作成功", {}).getJsonData()
        try:
            book = Book()
            book.book_name = request.POST.get("bookName")
            book.book_price = request.POST.get("bookPrice")
            book.book_type_id = request.POST.get("bookTypeId")
            book.book_count = request.POST.get("bookCount")
            book.book_publish = request.POST.get("bookPublish")
            book.book_publish_date = datetime.datetime.strptime(request.POST.get("bookPublishDate"), '%Y-%m-%d')
            book.book_introduction = request.POST.get("bookIntroduction")
            book.book_image_path = self.uploadImageFile(request, "file")
            book.create_time = time.strftime('%Y-%m-%d %X', time.gmtime())
            book.update_time = time.strftime('%Y-%m-%d %X', time.gmtime())
            book.save()
        except Exception as err:
            print(err)
            resultData = ResponseJson("false", "操作失败", {}).getJsonData()

        return JsonResponse(resultData, safe=False)


class EditBook(BaseView):
    def post(self, request):
        resultData = ResponseJson("true", "操作成功", {}).getJsonData()
        try:
            book = Book()
            book.book_id = request.POST.get("bookId")
            book.book_name = request.POST.get("bookName")
            book.book_price = request.POST.get("bookPrice")
            book.book_type_id = request.POST.get("bookTypeId")
            book.book_count = request.POST.get("bookCount")
            book.book_publish = request.POST.get("bookPublish")
            book.book_publish_date = datetime.datetime.strptime(request.POST.get("bookPublishDate"), '%Y-%m-%d')
            book.book_introduction = request.POST.get("bookIntroduction")
            #
            book.book_image_path = self.uploadImageFile(request, "file")
            book.update_time = time.strftime('%Y-%m-%d %X', time.gmtime())
            book.save()
        except Exception as err:
            print(err)
            resultData = ResponseJson("false", "操作失败", {}).getJsonData()

        return JsonResponse(resultData, safe=False)


class DeleteBook(BaseView):
    def post(self, request):
        resultData = ResponseJson("true", "操作成功", {}).getJsonData()
        try:
            book = Book()
            book.book_id = request.POST.get("bookId")
            book.delete()
        except Exception as err:
            print(err)
            resultData = ResponseJson("false", "操作失败", {}).getJsonData()

        return JsonResponse(resultData, safe=False)


class imageview(BaseView):
    def get(self, request):
        Book.object.filter()
        request.POST.get("bookId")
        queryset = models.Surveys.objects.filter(pk=pk).only('unique_code')  # only只显示指定的字段

        response = StreamingHttpResponse(iter_file(os.path.join("唯一码.xls")))  # 以二进制形式响应数据流
        response['Content-Type'] = 'application/octet-stream'  # 浏览器不识别的也会自动下载
        response['Content-Disposition'] = 'attachment; {}'.format(
            "filename*=utf-8''{}".format(quote("唯一码.xls"))
        return response

    def iter_file(path):
        size = 1024
        with open(path, "rb")as f:
            for data in iter(lambda: f.read(size), b''):
                yield data
